<?php
namespace app\admin\controller;
use app\model\Admin as AdminModel;
use app\model\AdminInfo as AdminInfoModel;
use think\Db;

use think\captcha\Captcha;
use app\lib\aliyun\Api as aliyunApi;


class Admin extends Base
{
    public $exception = ['login','getcaptcha','getloginsms','mlogincheck'];

    public function __construct(){
        $model = new AdminModel();
        $this->model = $model;
        parent::__construct();

        $page_info = $this->page_info;
        $page_info['title'] = '管理员';

        $this->assign([
            'model'=>$model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $model = $this->model;
        // $companys = Db::name('company')->select();
        // $companys = arrayParamExtract($companys,'id','name');

        $page_info = $this->page_info;
        $fields = [
            'account'=>['name'=>'用户名','type'=>'text','valids'=>['required']],
            'password'=>['name'=>'密码','type'=>'text','valids'=>['required']],
            'role'=>['name'=>'角色','type'=>'select1','params'=>$model->getRoleList()],
            'truename'=>['name'=>'姓名','type'=>'text'],
            'mobile'=>['name'=>'手机号码','type'=>'text'],
            'email'=>['name'=>'邮箱','type'=>'text'],
        ];
        if ($page_info['action'] == 'edit') {
            $fields['password']['placeholder'] = '留空，则不修改';
            $fields['password']['value'] = '';
            unset($fields['password']['valids']);
        }
        
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);

    }

    public function assignSearchs(){
        $model = $this->model;
        $departments = arrayParamExtract($departments,'id','name');

        $search_params = [
            [
                ['key'=>'account','name'=>'用户名','type'=>'text'],
                ['key'=>'truename','name'=>'姓名','type'=>'text'],
                ['key'=>'role','name'=>'角色','type'=>'select1_1','params'=>$model->getRoleList()],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

  

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'account','type'=>'like'],
            ['key'=>'truename','type'=>'like'],
            ['key'=>'role','type'=>'='],
            ['key'=>'company_id','type'=>'='],
            ['key'=>'department_id','type'=>'='],
        ];
        $map = getSearchParam($map_params);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        // 显示筛选
        $this->assignSearchs();

        $list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();
        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            $list['data'][$k]['role'] = $model->getRoleCn($vo['role']);
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    
    public function getLoginSms($mobile=''){
        if (strlen($mobile) != 11) {
            $this->error('手机号格式错误');    
        }
        $code = rand(1000,9999);
        $sms_res = sendSms($mobile,'您的验证码是：'.$code,'得力云');
        // $code = 1234;
        // $sms_res['status'] = 1;
        if ($sms_res['status'] == 1) {
            session('sms_'.$mobile,$code);
            $this->success('发送成功');    
        }else{
            $this->error($sms_res['msg']);  
        }
    }

    public function getCaptcha(){
        $captcha = new Captcha([        
            'codeSet'  => '1234567890', 
            'fontSize' => 20,
            'useCurve' => false,
            'imageH'   => 40,
            'length'   => 4,
            'reset'    => true
        ]);
        $data = $captcha->entry();
        return $data->getData();
    }

    public function login(){
        if (request()->isPost()) {
            $model = $this->model;
            $param = request()->param();

            if( !captcha_check($param['verify']) ){
                $this->error("验证码错误");
            }

            $data = $model->where('account',$param['account'])->find();
            // elseif (!in_array($data['role'], ['admin','wy','gj','yw','xz','cw'])) {
            //     $this->error("权限不足");
            // }
            if ( $data['password'] != md5($param['password']) ) {
                $this->error("账号或密码错误");
            }else{
                // elseif (!in_array($data['role'], ['admin','wy','gj','yw','xz','cw'])) {
                //     $this->error("权限不足");
                // }
                // 更新登录时间
                $model->where('id',$data['id'])->update(['login_time'=>time()]);

                session('cch_admin',$data);
                return redirect(url('index/index'));
            }
        }
        return view('login', [
            
        ]);
    }

    public function mloginCheck($mobile,$account){
        if (request()->isPost()) {
            $model = $this->model;
            $param = request()->param();

            if (strlen($param['mobile']) != 11) {
                $this->error('手机号格式错误');    
            }
            if (empty($param['verify']) || $param['verify'] != session('sms_'.$param['mobile'])) {
                $this->error('验证码错误');       
            }

            $data = $model->where([
                ['mobile','=',$param['mobile']],
                ['account','=',$param['account']],
            ])->find();
            if ( empty($data) ) {
                $this->error("账号不存在");
            }elseif (!in_array($data['role'], ['0','1'])) {
                $this->error("权限不足");
            }else{
                // 更新登录时间
                $model->where('id',$data['id'])->update(['login_time'=>time()]);
                session('sms_'.$param['mobile'],null);
                session('cch_admin',$data);
                // 手机验证码
                cookie('a_login_'.$data['mobile'],'1');
                return redirect(url('index/index'));
            }
        }
        return view('mlogin_check', [
            'mobile'=>$mobile,
            'account'=>$account
        ]);
    }

    // 修改密码
    public function changePwd(){
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'must'=>['old_pwd','new_pwd','confirm_pwd']
            ];
            $params = paramFilter(request()->param(),$fields);
            if (!empty($params['error_msg'])) {
                $this->error($params['error_msg']);
            }
            
            $id = $this->login_user['id'];
            $upwd = $model->where('id',$id)->value('password');
            if ($upwd != md5($params['old_pwd'])) {
                $this->error('原登录密码错误');
            }elseif ($params['new_pwd'] != $params['confirm_pwd']) {
                $this->error('新密码与确认密码不一致');
            }

            if ( $model->where('id',$id)->update([
                'password'=>md5($params['new_pwd'])
            ]) !== false ) {
                $this->success("编辑成功");
            }else{
                $this->error("编辑失败");
            }
        }

        $fields = [
            'old_pwd'=>['name'=>'旧密码','type'=>'text','value'=>'','placeholder'=>'请输入账号的原登录密码','valids'=>['required']],
            'new_pwd'=>['name'=>'新密码','type'=>'text','value'=>'','placeholder'=>'请输入新的登录密码','valids'=>['required']],
            'confirm_pwd'=>['name'=>'确认新密码','type'=>'text','value'=>'','placeholder'=>'请输入确认的登录密码','valids'=>['required']],
        ];
        $this->assign([
            'fields'=>$fields,
        ]);

        return view('common/save', [

        ]);
    }

    // 个人信息
    public function profile(){
        $model = $this->model;
        $id = $this->login_user['id'];

        if (request()->isPost()) {
            $fields = [
                'nomust'=>['truename','headimage','mobile']
            ];
            $params = paramFilter(request()->param(),$fields);
            if (!empty($params['error_msg'])) {
                $this->error($params['error_msg']);
            }
            
            if ( $model->where('id',$id)->update($params) !== false ) {
                $this->success("编辑成功");
            }else{
                $this->error("编辑失败");
            }
        }

        $fields = [
            'account'=>['name'=>'用户名','type'=>'disabled'],
            'role'=>['name'=>'角色','type'=>'disabled'],
            'truename'=>['name'=>'姓名','type'=>'text'],
            'headimage'=>['name'=>'头像','type'=>'file'],
            'mobile'=>['name'=>'手机号','type'=>'text']
        ];
        $this->assign([
            'fields'=>$fields,
        ]);

        $data = $model->where('id',$id)->find();
        $data['role'] = $model->getRoleCn($data['role']);
        return view('profile', [
            'data'=>$data
        ]);
    }

    

    public function add(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['account','password','role','truename'],
                'nomust'=>['mobile','email']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            $model = $this->model;
            if ($model->where('account',$save_data['account'])->count() > 0) {
                $this->error('用户名已存在');
            }
            $save_data['password'] = md5($save_data['password']);
        }

       
        $this->assign([
            
        ]);

        return parent::saveData($save_data);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        $model = $this->model;

        if (request()->isPost()) {
            $fields = [
                'must'=>['account','role','truename'],
                'nomust'=>['mobile','password','email']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            if (!empty($save_data['password'])) {
                $save_data['password'] = md5($save_data['password']);
            }else{
                unset($save_data['password']);
            }
        }
       

        return parent::updateData($id,$save_data);
    }


    public function logout(){
        session('cch_admin',null);
        return redirect(url('login'));
    }



    
    public function view(){
        $model = $this->model;
        $id = $this->login_user['id'];
        $data = $model->where('id',$id)->find();
        return view('view', [
            'data'=>$data
        ]);
    }

    // public function sdzjye(){
    //     $ower_id = '1860553274599172';
    //     $difference = 574.123;
    //     $api_controller = new aliyunApi();
    //     $result = $api_controller->ChangeResellerConsumeAmount($ower_id,$difference,uuidCreate());
    //     dump($result);die;
    // }
}
